package com.example.wan1.view.web;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;

import com.example.wan1.R;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.utils.ColorTheme;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebActivity extends AppCompatActivity {

    @BindView(R.id.iv_arrow)
    ImageView mIvArrow;
    @BindView(R.id.web_title)
    TextView mWebTitle;
    @BindView(R.id.web_collect)
    ImageView mWebCollect;
    @BindView(R.id.web_tbar)
    Toolbar mWebTbar;
    @BindView(R.id.web_pg)
    ProgressBar mWebPg;
    @BindView(R.id.web)
    WebView mWeb;
    @BindView(R.id.web_gotop)
    FloatingActionButton mGoTop;

    private boolean mIsDownload = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ColorTheme newTheme = new ColorTheme(this);
        newTheme.loadTheme();
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);

        /*getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);*/

        setSupportActionBar(mWebTbar);

        int color = ToolsUtils.getThemeColor(this);
        if (color != 0) {
            mWebTbar.setBackgroundColor(color);
            StatusBarUtil.setColor(this, color, 0);
        }

        initSet(mWeb.getSettings());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mWeb.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> judgeTopAndBottom());
        }

        CookieManager mCookieManager = CookieManager.getInstance();
        mCookieManager.setAcceptCookie(true);
        mCookieManager.setAcceptThirdPartyCookies(mWeb, true);


//        mWeb.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//解决白屏问题
        //mWeb.setLayerType(View.LAYER_TYPE_HARDWARE,null);//开启硬件加速
        mWeb.setNetworkAvailable(true);

        ArticleBean bean = HandleCollectTool.getInstance().getArticle();
        if (bean != null) {
            if (bean.isCollect())
                mWebCollect.setImageResource(R.mipmap.heart_red);
            else
                mWebCollect.setImageResource(R.mipmap.heart_gray);
        }

        /*runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (getIntent().getStringExtra("url").equals("http://gk.link/a/103Ei"))
                    mWeb.loadUrl("https://market.geekbang.org/activity/channelcoupon/16?utm_source=web&utm_medium=wananzhuo&utm_campaign=changweiliuliang&utm_term=zhanghongyang003&utm_content=0530");
                else
                    mWeb.loadUrl(getIntent().getStringExtra("url"));
            }
        });*/

        if (getIntent().getStringExtra("url").equals("http://gk.link/a/103Ei"))
            mWeb.loadUrl("https://market.geekbang.org/activity/channelcoupon/16?utm_source=web&utm_medium=wananzhuo&utm_campaign=changweiliuliang&utm_term=zhanghongyang003&utm_content=0530");
        else if (getIntent().getStringExtra("url").contains("/blog/show/")
                && !getIntent().getStringExtra("url").contains(Constants.BASE_URL) && !getIntent().getStringExtra("url").contains(Constants.BASE_URL_1))
            mWeb.loadUrl(Constants.BASE_URL + getIntent().getStringExtra("url"));
        else
            mWeb.loadUrl(getIntent().getStringExtra("url"));

        //设置WebChromeClient类
        mWeb.setWebChromeClient(new WebChromeClient() {


            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (title != null)
                    mWebTitle.setText(title);
            }

            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                //因为关掉activity的时候进度变成了10,所以报空指针的错误
                if (mWebPg != null) {
                    if (newProgress < 100) {
                        mWebPg.setVisibility(View.VISIBLE);
                        mWebPg.setProgress(newProgress);
                    } else if (newProgress == 100) {
                        mWebPg.setVisibility(View.GONE);
                    }

                }

            }

        });
        mWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //打开第三方应用
                try {
                    //处理intent协议
                    if (url.startsWith("intent://")) {
                        Intent intent;
                        try {
                            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                            intent.addCategory("android.intent.category.BROWSABLE");
                            intent.setComponent(null);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                                intent.setSelector(null);
                            }
                            List<ResolveInfo> resolves = getApplication().getPackageManager().queryIntentActivities(intent, 0);
                            if (resolves.size() > 0) {
                                startActivityIfNeeded(intent, -1);
                            } else {
                                mIsDownload = true;
                                Toast.makeText(WebActivity.this, "intent未安装", Toast.LENGTH_SHORT).show();
                            }
                            return true;
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                    // 处理自定义scheme协议
                    else if (!url.startsWith("http")) {
                        try {
                            // 以下固定写法
                            final Intent intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(url));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            startActivity(intent);
                        } catch (Exception e) {
                            mIsDownload = true;
                            // 防止没有安装的情况
                            e.printStackTrace();
                            Toast.makeText(WebActivity.this, "您所打开的第三方App未安装！", Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    } else {
                        //Log.e("should", "shouldOverrideUrlLoading: " + url.indexOf("redirect"));
                        if (url.indexOf("redirect") == -1) {
                            view.loadUrl(url);
                            return true;
                        } else
                            return false;

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                //设定加载开始的操作
                if (mWebTitle != null)
                    mWebTitle.setText(getIntent().getStringExtra("url"));
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                //设定加载结束的操作
                if (mWebTitle != null && !view.getTitle().equals(getIntent().getStringExtra("title"))) {
                    mWebTitle.setText(getIntent().getStringExtra("title"));
                    mWebTitle.requestFocus();
                    //mWebTitle.setHorizontallyScrolling(true);
                }

                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(WebActivity.this, "errorCode:" + errorCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);注意一定要去除这行代码，否则设置无效。
                // handler.cancel();// Android默认的处理方式
                handler.proceed();// 接受所有网站的证书
                // handleMessage(Message msg);// 进行其他处理
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                String fileName = request.getUrl().getLastPathSegment();
                if (fileName != null) {
                    boolean isAd = false;
                    for (String str : forbiddenAds) {
                        if (fileName.equals(str)) {
                            isAd = true;
                        }
                    }
                    if (isAd) {
                        return new WebResourceResponse(null, null, null);
                    }
                }
                return super.shouldInterceptRequest(view, request);
            }

        });

        //mWeb.requestFocus();

        mWeb.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            if (mIsDownload) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse(url);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(uri);
                startActivity(intent);
            }
            mIsDownload = true;//重置为初始状态
        });

        mWebTbar.setOnMenuItemClickListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.web_item1:
                    //复制 https://blog.csdn.net/seashine_yan/article/details/75426007
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                    ClipData clipData = ClipData.newPlainText(null, mWeb.getUrl());
                    // 把数据集设置（复制）到剪贴板
                    cm.setPrimaryClip(clipData);
//                        cm.setText(mWeb.getUrl());
                    Toast.makeText(WebActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.web_item2:
                    mWeb.reload();
                    break;
                case R.id.web_item3:
                    //https://blog.csdn.net/bzlj2912009596/article/details/80673555
                    Uri uri = Uri.parse(mWeb.getUrl());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    break;
            }
            return false;
        });

        //导航栏着色
        if (ToolsUtils.isOpenNavigationBar(this) && !ToolsUtils.getNightMode(this)) {
            Window window = getWindow();
            /*getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);*/
            if (ToolsUtils.getThemeColor(this) != 0)
                window.setNavigationBarColor(ToolsUtils.getThemeColor(this));
            else
                window.setNavigationBarColor(ToolsUtils.getAttrValue(this));
        }
    }

    @SuppressLint("RestrictedApi")
    private void judgeTopAndBottom() {
        if (mWeb.getContentHeight() * mWeb.getScale() == (mWeb.getHeight() + mWeb.getScrollY())) {
            //已经处于底端
            mGoTop.setVisibility(View.VISIBLE);
        }

        if (mWeb.getScrollY() == 0) {
            //处于顶端
            mGoTop.setVisibility(View.GONE);
        }
    }

    /***
     * 销毁Webview
     */
    @Override
    protected void onDestroy() {
        if (mWeb != null) {
            mWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWeb.clearHistory();

            ((ViewGroup) mWeb.getParent()).removeView(mWeb);
            mWeb.destroy();
            mWeb = null;
        }
        RxBus.getDefault().postSticky(new CollectEvent(HandleCollectTool.getInstance().getType()));
        super.onDestroy();
    }

    /***
     * 点击返回上一页面而不是退出浏览器
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWeb.canGoBack()) {
            mWeb.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /***
     * web的初始化
     * @param webSettings 设置
     */
    private void initSet(WebSettings webSettings) {
        //设置缓存
        webSettings.setAppCacheEnabled(false);
        //设置缓存路径
        webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
        // 是否保存表单数据
        webSettings.setSaveFormData(true);
        // 是否当webview调用requestFocus时为页面的某个元素设置焦点，默认值 true
        webSettings.setNeedInitialFocus(true);
        // 资源访问
        webSettings.setAllowContentAccess(true);// 是否可访问Content Provider的资源，默认值 true
        webSettings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        webSettings.setAllowFileAccessFromFileURLs(true);// 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        webSettings.setAllowUniversalAccessFromFileURLs(true);// 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 用户是否需要通过手势播放媒体(不会自动播放)，默认值 true
            webSettings.setMediaPlaybackRequiresUserGesture(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 5.0以上允许加载http和https混合的页面(5.0以下默认允许，5.0+默认禁止)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 是否在离开屏幕时光栅化(会增加内存消耗)，默认值 false
            webSettings.setOffscreenPreRaster(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //其他细节操作
        //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //关闭webview中缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        // 资源加载
        webSettings.setLoadsImagesAutomatically(false); //支持自动加载图片
        webSettings.setBlockNetworkImage(false);        // 禁止加载网络图片
        webSettings.setBlockNetworkLoads(false);       // 禁止加载所有网络资源

        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //声明WebSettings子类 ********************end******************
        //不能点击"csdn中的阅读全文"http://www.shuchengxian.com/article/DGjJRCnMhL.html
        //定位
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);//不能点击"csdn中的阅读全文
        webSettings.setGeolocationDatabasePath(getApplication().getFilesDir().getPath());
    }

    /***
     * 创建menu
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.web_menu, menu);//加载menu布局
        return true;
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        if (menu != null) {
            if (menu.getClass() == MenuBuilder.class) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {

                }
            }
        }
        return super.onPrepareOptionsPanel(view, menu);
    }

    @SuppressLint("RestrictedApi")
    @OnClick({R.id.web_gotop, R.id.iv_arrow, R.id.web_collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.web_gotop:
                mWeb.pageUp(true);
                break;
            case R.id.iv_arrow:
                finish();
                break;
            case R.id.web_collect:
                if (!UserManager.getInstance().isLogin()) {
//                if (!AppUtils.isLogin()) {
                    JumpTool.goLogin(this);
                    return;
                }
                //需要先判断是否收藏，如果收藏那么就取消收藏，如果是未收藏状态就收藏文章
                ArticleBean article = HandleCollectTool.getInstance().getArticle();
                if (article == null) {
                    ToastUtils.showToast("出现异常~~");
                    return;
                }
                if (article.isCollect()) {
                    HandleCollectTool.getInstance().cancelList();
                    mWebCollect.setImageResource(R.mipmap.heart_gray);
                } else {
                    HandleCollectTool.getInstance().collectIn();
                    mWebCollect.setImageResource(R.mipmap.heart_red);
                }
                //文章列表的红心怎么收藏和取消？等到web界面销毁的时候，发送事件，通知更新，这里似乎不太妥
                break;
        }
    }

    /**
     * 设置 app 不随着系统字体的调整而变化
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    private String[] forbiddenAds = new String[]{"ads", "adsbygoogle.js", "mediaAdLoad", "getMediaAd"};
}
